/**
 * Copyright (C) 2006 ChangSha WangWin Science & Technology CO,.LTD. All rights reserved.
 * WangWin PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.kingcore.pda.core.filter;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

/**
 * <p>java类文件的说明...</p>
 * @author Zeven on 2007-2-14
 * @version	1.0
 * @see		Object#equals(java.lang.Object)
 * @see		Object#hashCode()
 * @see		HashMap
 * @since	JDK5
 */

public class DirectoryRequestFilter implements Filter {

	protected static Logger log = Logger.getLogger( DirectoryRequestFilter.class );
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
		
		// TODO Auto-generated method stub
		String[] welcomeFiles={"index.html",
				   "index.jsp",
				   "welcome.html",
				   "welcome.jsp",
				   "main.jsp"};
		
		String path= ((HttpServletRequest) (request)).getRequestURI();

		String fullPath=path;
		//log.info("Dir  doFilter " );
		//log.debug("aa path= " + path);
		int pos = path.indexOf("/",1);
		if (pos>-1) {
			path = path.substring( path.indexOf("/",1) );
		}
		//log.info("path= " + path);
		if(path.endsWith("/")){	//属于目录请求
			//((HttpServletRequest) (request)).getSession().getServletContext().
			
			String realPath = request.getRealPath( path  );
			//log.info("Client is " + request.getRemoteHost() +", realPath = " + realPath);
			//System.out.println("realPath= " + realPath);
			boolean hasIndex = false;
			File file = null;
			for(int i=0; i<welcomeFiles.length; i++){
				file = new File( realPath + welcomeFiles[i] );
				//System.out.println("file= " + realPath + welcomeFiles[i]);
				if(file.exists()){
					hasIndex = true ;
					break;
				}
			}
			if( !hasIndex ){
				System.out.println("fullPath------:" + fullPath);
				request.getRequestDispatcher("/database/projectFileList.jsp?path="+fullPath +"&realPath="+realPath ).forward(request, response) ;
				return ;
				
			}
		}
		
		filterChain.doFilter(request,response);
	}

	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
